package com.chrilwe.pigpig.filesystem.common.util;

import java.io.IOException;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;

/**
 *  文件管理工具
 * @author chrilwe
 * @date 2020-9-12
 */
public class FastDfsUtil {
	
	private static TrackerServer trackerServer;
	private static StorageServer storeStorage;
	private static StorageClient1 storageClient;

	static {
		try {
			ClassPathResource classpath = new ClassPathResource("fastdfs");
			String path = classpath.getURL().getPath() + "/fastdfs_client.conf";
			ClientGlobal.init(path);
			TrackerClient trackerClient = new TrackerClient();
			trackerServer = trackerClient.getConnection();
			
			storeStorage = trackerClient.getStoreStorage(trackerServer);
			storageClient = new StorageClient1(trackerServer, storeStorage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String upload(byte[] data,String ext,NameValuePair[] nvp) {
		try {
			String url = storageClient.upload_file1(data, ext, nvp);
			return url;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(storeStorage != null) {
				try {
					storeStorage.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(trackerServer != null) {
				try {
					trackerServer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	private void delete(String storagePath) {
		try {
			storageClient.delete_file1(storagePath);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(storeStorage != null) {
				try {
					storeStorage.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(trackerServer != null) {
				try {
					trackerServer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
